var express = require('express');
var router = express.Router();
var crypto=require('crypto');
var jssdk=require('../public/javascripts/jssdk.js');
var wechat =require('wechat');
var appid='wxa4a67ab74a1eedd9';
var appsecret='c93630c3edc1381ff35d3fef0da55e9c';

var request=require('request');
var cheerio=require('cheerio');
var User=require('../public/models/user.js');
var Conversation=require('../public/models/conversation.js');
var moment=require('moment');
var lodash=require('lodash');
var WechatAPI = require('wechat-api');
var api = new WechatAPI(appid, appsecret);
//var XMLParser=require('express-xml-bodyparser');
/* GET home page. */
//获取signPackage   //作用还不是很明白
var getSignPackage=function(req,res,next){
    console.log({requrl:req.url,reqoriginalUrl:req.originalUrl});
    //var pathname=req.originalUrl.split('?').shift();
    //jssdk.getSignPackage('http://119.23.206.146'+req.url,function(err,signPackage){
    jssdk.getSignPackage('http://120.78.206.253'+req.url,function(err,signPackage){
        if(err){
            return next(err);
        }
        req.signPackage=signPackage;
        next();
    })
};
router.get('/wechat/hello',getSignPackage, function(req, res, next) {
    jssdk.getSignPackage(req.url,function(err,signPackage){  //
        if(err){
            return next(err);
        }
        //jade template   但这是ejs？
        res.render('index', {
        title: 'Hello wechat',
        signPackage:signPackage,
        pretty:true
        });
    })

});
//原始写法  不用WECHAT模块YY
var handleWechatReq0=function(req,res,next){

  //const {signature,timestamp,nonce,echostr}=req.query;  //query是url？后面携带的参数吗
  var signature = req.query.signature;  //query是url？后面携带的参数吗
  var timestamp = req.query.timestamp;
  var nonce = req.query.nonce;
  var echostr=req.query.echostr;
  console.log('signature:'+signature+'timestam1:'+timestamp+'nonce2:'+nonce+'echostr3:'+echostr);
  //console.log('11');
  if(!signature ||!timestamp||!nonce){ //post请求没有||!echostr
    return res.send('invalid req0');
  }
  if(req.method==='POST'){
	  console.log('handleWechatReq+POST:',{body:req.body,query:req.query}); //这种写法才能显示xml  步解析则req.body
	  //console.log('handleWechatReq+POST:'+req.body+'query:'+req.query);
  }
  if(req.method==='GET'){
    console.log('handleWechatReq+GET:',{get:req.body});
	  //console.log('handleWechatReq+GET:'+'get:'+req.body)
	  if(!echostr){  //get 需要校验
		  return res.send('invalid req');
	  }
  }
  var token='weixin1';
  var params=[token,timestamp,nonce];
  console.log(params);
  params.sort();   //按字典即字母顺序排序
  //var str=params.join('');//将所有数据元素放入字符串
  var hash=crypto.createHash('sha1');//进行sha1加密
  var sign=hash.update(params.join('')).digest('hex');
  if(signature===sign){  //对比，标识该请求来源于微信为空
    //res.set('Content-Type','text/xml');
    if(req.method==='GET'){
      res.send(echostr?echostr:"invid req");
    }
    else{
      var tousername=req.body.xml.tousername[0].toString();
      var fromusername=req.body.xml.fromusername[0].toString();
      var createtime=Math.round(Date.now()/1000);
      var msgtype=req.body.xml.msgtype[0].toString();
      var content=req.body.xml.content[0].toString();
      var msgid=req.body.xml.msgid[0].toString();
      //var response1='<xml><ToUserName><![CDATA[${fromusername}]]></ToUserName><FromUserName><![CDATA[${tousername}]]></FromUserName><CreateTime>${createtime}</CreateTime><MsgType><![CDATA[${msgtype}]]></MsgType><Content><![CDATA[${content}]]></Content></xml>';  //wu id
      var response1='<xml>' +
          '<ToUserName><![CDATA[' +
          fromusername +
          ']]></ToUserName> ' +    //注意不要有空格
          '<FromUserName><![CDATA[' +
          tousername +
          ']]></FromUserName> ' +
          '<CreateTime>' +
          createtime +
          '</CreateTime> ' +
          '<MsgType><![CDATA[' +
          msgtype +
          ']]></MsgType> ' +
          '<Content><![CDATA[' +
          content +
          ']]></Content> ' +
          '</xml>';
      res.set('Content-Type','text/xml');

      //res.send('');   //huifu
      //console.log(tousername);
      //console.log(fromusername);
      //console.log(createtime);
      //console.log(msgtype);
      //console.log(content);
      //console.log(msgid);
      //return res.send('1212');
      console.log(response1);
       res.send(response1);  //meiyou return baocuo

    }
  }
  else{
    res.send('invaid req1')
  }
};
var config={
    token:'weixin1',
    //appId:'wxa4a67ab74a1eedd9'
    appId:'wx9cfa541517988efa'
};

//查询用户信息-自写
var handleWechatReq1=wechat(config,function(req,res,next){
    var message=req.weixin; //消息在req.weixin上
    // var appID='wxa4a67ab74a1eedd9';     /原2727269494测试号  
    // var appsecret='c93630c3edc1381ff35d3fef0da55e9c';
	var appID='wx9cfa541517988efa';
    var appsecret='1a57ce95f0af172ac3b026db46c2ee58';
    var accurl='https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx9cfa541517988efa&secret=1a57ce95f0af172ac3b026db46c2ee58';
    var openid=req.query.openid;
    console.log(message);
    console.log('openid:'+req.query.openid);
    //res.reply('hello');
    //if(message.MsgType==='event'&&message.Content==='subscribe'){
        request.get(accurl,function(err,res,body){ //获取accesstoken
            if(err){   //必须写
                console.log(err);
            }
            console.log(body);
            console.log('body1:'+body);
            var token=JSON.parse(body).access_token;  //需要解析
            console.log('解析TOKEN:'+token);
            //var tokenstr=JSON.stringify(token);  //放入URL应该是字符串,不必
            //var openid='o2UzewtkQY2uT9g9LonGhLem-mZ0';
            //var url='https://api.weixin.qq.com/cgi-bin/user/info?access_token=${token}&openid=o2UzewtkQY2uT9g9LonGhLem-mZ0';  //用￥｛｝无效?
            var url='https://api.weixin.qq.com/cgi-bin/user/info?access_token='+token+'&openid=o2UzewtkQY2uT9g9LonGhLem-mZ0';
            request.get(url,function(err,res,body){  //通过accesstoken获取用户信息
                if(err){
                    console.log(err)
                }
                console.log('req2:'+body);
                console.log('有用户，他是：'+JSON.parse(body).nickname)
            })

        });
    //}
        res.reply(message.Content);
});
//处理textmessage的函数
var handleTextMessage=function(req,res,next){
    var message=req.weixin; //消息在req.weixin上
    console.log('文本消息:'+message.Content);
    //res.set('Content-Type','text/xml');
    if(message.MsgType!=='text'){
        return res.reply('无法处理非text的消息类型');
    }
    if(!message.Content){
        return res.reply('你没有提出任何问题');
    }
    var keyword=message.Content;    //输入的内容  即提出的问题
    request.get({
            url: 'https://www.baidu.com/s?word=' + encodeURIComponent(keyword),  //需要解码keyword
            headers:{
                //'Cookie':'BAIDUID=74F57E28F6D72675AE570796F5A39B62:FG=1; BIDUPSID=74F57E28F6D72675AE570796F5A39B62; PSTM=1471705639; BDRCVFR[8gzLr2xelNt]=IdAnGome-nsnWnYPi4WUvY; H_PS_PSSID=1448_18241_11616_20857_20836',
                'User-Agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36'  //谷歌浏览器network里面的头  带进去  不然反爬虫
            }
        },
        function(err,res1,body){   //这里不能写res  会和外层的res混
            if(err){
                //console.log(err);
                console.error(err);
                return res.reply('寻找问题答案发生错误')
            }
            //console.log('cherio-body:'+body);
            var $=cheerio.load(body);
            var results=$('.result.c-container');  //百度结果的每一条形成的结果数组  中间没有空格
            console.log('问题搜索结果数:'+results.length);
            //results.each(function(i,item){   // 注意与原生的差异
            //    var ndItem=$(item);
            //    console.log(ndItem.find('h3 a').attr('href'));   //每一条搜索结果的a链接
            //    console.log(ndItem.find('.c-abstract').text());//每一条搜索结果的简介
            //})
            if(results.length===0){
                return res.reply('没有找到问题答案');
            }
            var result=$(results.get(0));
            var answer=result.find('.c-abstract').text();
            res.reply(answer? answer:'找到了空答案');

            //保存问答
            var conversation=new Conversation({
                user:req.user,
                question:message.Content,
                answer:answer,
                createAt:new Date()
            });
            conversation.save(function(err,conversation1) {
                if (err) {
                    return console.error('conversation save error:', err);
                }
                //更新会话次数
                //console.log('req', req);
                //console.log('问答req.user', req.user);
                console.log(' req.user.conversationCount赋值前:'+req.user.conversationCount);
                req.user.conversationCount = req.user.conversationCount + 1;
                console.log(' req.user.conversationCount:'+req.user.conversationCount);
                req.user.save(function (err1, u) {
                    if (err1) {
                        return console.error('conversationCount save error:', err1);
                    }
                    console.log('u:'+u);
                    console.log('更新问答次数存储成功req.user')
                });
            })
        }
    );
};
//只处理事件类型消息的函数
var handleEventMessage=function(req,res,next){
    var message=req.weixin;   //用户点击的事件消息

    var event=message.Event;
    var eventKey=message.EventKey;
    if(event==='CLICK'){
        if(eventKey==='history'){    //问答历史？
            res.reply('http://119.23.206.146/api/wechat/history/'+req.user._id.toString());
        }
    }
    else{
        console.log('无法处理的事件类型click中的')
    }

};

var handleWechatReq=wechat(config,function(req,res,next){
    var message=req.weixin; //消息在req.weixin上
    console.log({message:message.Content,query:req.query});
    console.log('收到消息')
    console.log('event:'+JSON.stringify(message));
    //res.set('Content-Type','text/xml');
    if(message.MsgType=='text'){
        handleTextMessage(req,res,next);
    }
    else if(message.MsgType=='event'){
        handleEventMessage(req,res,next);
    }
    else if((message.MsgType == 'event') && (message.Event == 'subscribe')) {
        //var refillStr = "<a href=\"http://your_IP/weixin/refill?weixinId=" + message.FromUserName + "\">1. 点击记录团队充值"+message.ToUserName+"</a>"
        //var consumeStr = "<a href=\"http://your_IP/weixin/consume?weixinId=" + message.FromUserName + "\">2. 点击记录团队消费"+message.FromUserName+"</a>"
        //var deleteStr = "<a href=\"http://your_IP/weixin/delete?weixinId=" + message.FromUserName + "\">3. 点击回退记录"+message.MsgType+"</a>"
        //var historyStr = "<a href=\"http://your_IP/weixin/history?weixinId=" + message.FromUserName + "\">4. 点击查询历史记录"+message.Event+"</a>"
        //
        //var emptyStr = "          ";
        //var replyStr = "感谢你的关注！" + "\n"+ emptyStr + "\n" + refillStr + "\n"+ emptyStr + "\n" + consumeStr
        //    + "\n"+ emptyStr + "\n" + deleteStr + "\n"+ emptyStr + "\n" + historyStr;
        //res.reply(replyStr);
        var res_str="感谢您关注重庆市永川区优兵蔬菜种苗有限责任公司！本公司经营各种蔬菜、荷花莲藕种子，家族企业，配有观光农业旅游景点。点击下方菜单，可获取各种种子的图文展示，wifi下查看体验更佳~"
        res.reply(res_str);
    }
   else{
        res.reply('handleWechatReq无法处理的消息类型')
    }

    //res.reply(message.Content);   //wechat模块自己改动出过错  不能写2个res。reply
    //res.reply({
    //    content: 'text object',
    //    type: 'text'
    //});

    //if (message.Content === 'dark') {
    //    res.reply('dark is sb');
    //}
});
//自动回复
//router.use(express.query());


//处理用户同步
var handleuserSync=function(req,res,next){
    if(!req.query.openid){  //openid不存在

        return next();
    }
    var openid=req.query.openid;
    User.findOne({openid:openid}).exec(function(err,user){  //如果存在就拿去查询，取openid相应的user返回
        if(err){
            console.log(err);
            return next(err);
        }
        if(user){   //如果这个user存在  放进req对象
            req.user=user;
        }
        console.log('crate new user:'+openid);
        var newUser=new User({  // 如果不存在以这个openid新建一个user
            openid:openid,
            createAt:Date.now(),
            coversationCount:0
        });
        newUser.save(function(e,u){  //存储新user应回调u就是user
            if(e){
                return next(e);
            }
            req.user=u;
            next();

        })
    })
};

router.get('/api/wechat',handleWechatReq);  //消息是post请求，数据格式是xml，需要解析
router.post('/api/wechat',handleuserSync,handleWechatReq);
router.get('/api/wechat/history/:userid',getSignPackage,function(req,res,next){
    console.log('req.params.userid:'+req.params.userid);
    if(!req.params.userid){
        return next(new error('非法请求，缺少userid'));
    }
    User.findOne({_id:req.params.userid}).exec(function(e,user){
        console.log('User.findOne-user:'+user);
        if(e||!user){
            //return next(new error('为找到用户'));   //莫名出错
            return console.log('为找到用户')
        }
        Conversation.find({ }).sort('-createAt').limit(20).exec(function(e1,conversations){   //注意find里面的查询条件 为空就是查询所有
            if(e1){
                return next(new error('查找问题历史出错'));
            }
            console.log('conversations:'+conversations);
            res.render('history', { title: 'history问答页面',
                user:user,
                conversations:conversations,
                moment:moment,
                signPackage:req.signPackage,
                pretty:true
            });
            //res.jsonp({user:user,conversation:conversation});
        });
        console.log('find user:'+user);
    });
});  //find 查询制定用户还不行
//随机
router.get('/api/wechat/random',getSignPackage,function(req,res,next){
        Conversation.find({ }).limit(100).exec(function(e1,conversations){   //注意find里面的查询条件 为空就是查询所有
            if(e1){
                return next(new error('随机问答出错'));
            }
           var shuffled=lodash.shuffle(conversations).slice(0,20); //随机算法
            res.render('history', {
                title:'随机问答-Dark呢',
                conversations:shuffled,
                moment:moment,
                signPackage:req.signPackage,
                pretty:true
            });
            //res.jsonp({shuffled:shuffled});
        });
});
//改写问答
//router.get('/api/wechat', wechat('weixin1', function (req, res, next) {
//    // 微信输入信息都在req.weixin上
//    var message = req.weixin;
//
//    if((message.MsgType == 'event') && (message.Event == 'subscribe')) {
//        //var refillStr = "<a href=\"http://your_IP/weixin/refill?weixinId=" + message.FromUserName + "\">1. 点击记录团队充值"+message.ToUserName+"</a>"
//        //var consumeStr = "<a href=\"http://your_IP/weixin/consume?weixinId=" + message.FromUserName + "\">2. 点击记录团队消费"+message.FromUserName+"</a>"
//        //var deleteStr = "<a href=\"http://your_IP/weixin/delete?weixinId=" + message.FromUserName + "\">3. 点击回退记录"+message.MsgType+"</a>"
//        //var historyStr = "<a href=\"http://your_IP/weixin/history?weixinId=" + message.FromUserName + "\">4. 点击查询历史记录"+message.Event+"</a>"
//        //
//        //var emptyStr = "          ";
//        //var replyStr = "感谢你的关注！" + "\n"+ emptyStr + "\n" + refillStr + "\n"+ emptyStr + "\n" + consumeStr
//        //    + "\n"+ emptyStr + "\n" + deleteStr + "\n"+ emptyStr + "\n" + historyStr;
//        //res.reply(replyStr);
//        var res_str="感谢您关注重庆市永川区优兵蔬菜种苗有限责任公司！本公司经营各种蔬菜、荷花莲藕种子，家族企业，配有观光农业旅游景点。点击下方菜单，可获取各种种子的图文展示，wifi下查看体验更佳~"
//        res.reply(res_str);
//    }
//}));
router.get('/api/wechat/random1',getSignPackage,function(req,res,next){
    Conversation.find({ }).limit(100).exec(function(e1,conversations){   //注意find里面的查询条件 为空就是查询所有
        if(e1){
            return next(new error('改写问答出错'));
        }
        Conversation.find({ }).sort('-createAt').limit(20).exec(function(e1,conversations){   //注意find里面的查询条件 为空就是查询所有
            if(e1){
                return next(new error('查找问题历史出错'));
            }
            console.log('conversations:'+conversations);
            res.render('history', { title: 'history问答页面',
                user:user,
                conversations:conversations,
                moment:moment,
                signPackage:req.signPackage,
                pretty:true
            });
            //res.jsonp({user:user,conversation:conversation});
        });
    });
});
router.get('/api/wechat/ercai',getSignPackage,function(req,res,next){

        res.render('ercai', {
            title:'儿菜',
            moment:moment,
            signPackage:req.signPackage,
            pretty:true
        });
});
router.get('/api/wechat/ercai_more',getSignPackage,function(req,res,next){

    res.render('ercai_more', {
        title:'儿菜-图片专区',
        moment:moment,
        signPackage:req.signPackage,
        pretty:true
    });
});
router.get('/api/wechat/luobo',getSignPackage,function(req,res,next){

    res.render('luobo', {
        title:'萝卜',
        moment:moment,
        signPackage:req.signPackage,
        pretty:true
    });
});
router.get('/api/wechat/luobo_more',getSignPackage,function(req,res,next){

    res.render('luobo_more', {
        title:'萝卜',
        moment:moment,
        signPackage:req.signPackage,
        pretty:true
    });
});
router.get('/api/wechat/zhacai',getSignPackage,function(req,res,next){

    res.render('zhacai', {
        title:' 榨菜',
        moment:moment,
        signPackage:req.signPackage,
        pretty:true
    });
});
router.get('/api/wechat/qita',getSignPackage,function(req,res,next){

    res.render('qita', {
        title:' 其他蔬菜',
        moment:moment,
        signPackage:req.signPackage,
        pretty:true
    });
});
router.get('/api/wechat/lianou',getSignPackage,function(req,res,next){

    res.render('lianou', {
        title:' 莲藕',
        moment:moment,
        signPackage:req.signPackage,
        pretty:true
    });
});
router.get('/api/wechat/hehua',getSignPackage,function(req,res,next){

    res.render('hehua', {
        title:' 荷花',
        moment:moment,
        signPackage:req.signPackage,
        pretty:true
    });
});
router.get('/api/wechat/hehua_more',getSignPackage,function(req,res,next){

    res.render('hehua_more', {
        title:' 荷花',
        moment:moment,
        signPackage:req.signPackage,
        pretty:true
    });
});
router.get('/api/wechat/about',getSignPackage,function(req,res,next){

    res.render('about', {
        title:' 联系我们',
        moment:moment,
        signPackage:req.signPackage,
        pretty:true
    });
});
//auto reply
router.get('/api/wechat', wechat(config, wechat.text(function (message, req, res, next) {
    //
    var message = req.weixin;
     logger.log("info", message);

    res.reply('Message Send To Bot Completed , Wait Response.');

    api.sendText(message.FromUserName, '感谢您关注重庆市永川区优兵蔬菜种苗有限责任公司！本公司经营各种蔬菜、荷花莲藕种子，家族企业，配有观光农业旅游景点。点击下方菜单，可获取各种种子的图文展示，wifi下查看体验更佳~', function (err, result) {
        if (err) {
            logger.log('error', err);
        }
        logger.log('info', 'reply message success');
    });

})))
module.exports = router;
